<?php

class AdController extends BackendController
{

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new AdForm();
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		if(isset($_POST['AdForm']))
		{
            $value = array(
                'ad' => $_POST['AdForm']['ad'],
                'link' => $_POST['AdForm']['link'],
                'target' => $_POST['AdForm']['target'],
                'desc' => $_POST['AdForm']['desc'],
                'created_at' => time(),
                'updated_at' => time(),
            );
            $_POST['AdForm']['value']=json_encode($value);
			$model->attributes = $_POST['AdForm'];
            //var_dump($_POST['AdForm']);echo'<br><br>';
			//var_dump($model->attributes);//exit;
			if($model->save())
                Yii::app()->user->setFlash('success', Yii::t('app', 'Create Success'));
				$this->redirect(array('index','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=self::loadModel($id);
		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);
		if(isset($_POST['AdForm']))
		{
			$value = array(
                'ad' => $_POST['AdForm']['ad'],
                'link' => $_POST['AdForm']['link'],
                'target' => $_POST['AdForm']['target'],
                'desc' => $_POST['AdForm']['desc'],
                'created_at' => json_decode($model->attributes['value'])->created_at,
                'updated_at' => time(),
            );

            $_POST['AdForm']['value']=json_encode($value);
            $model->attributes = $_POST['AdForm'];
			if($model->save())
                Yii::app()->user->setFlash('success', Yii::t('app', 'Update Success'));
				$this->redirect(array('index','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		$this->loadModel($id)->delete();

		// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
		if(!isset($_GET['ajax']))
            Yii::app()->user->setFlash('success', Yii::t('app', 'Delete Success'));
			$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('index'));
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
        $criteria = new CDbCriteria();
        $criteria->order = 'sort ASC,id DESC';
        $criteria->condition = 'type=3';
        $count = Banner::model()->count($criteria);
        $pages = new CPagination($count);
        $pages->pageSize = 13;
        $pages->applyLimit($criteria);
        $list = Banner::model()->findAll($criteria);
        //var_dump($list[0]->attributes['value']);
        //$lists = json_decode($list['atrributes']['value']);
        //var_dump($lists);
        $this->render('index', array('count'=>$count,'list' => $list, 'pages' => $pages));

	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new AdForm('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Banner']))
			$model->attributes=$_GET['Banner'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

    /**
     * 批量删除内容
     * @param $id
     * @throws CDbException
     * @throws CHttpException
     */
    public function actionDeleteAll()
    {
        $request = Yii::app()->request;
        if (!$request->isAjaxRequest || !$request->isPostRequest)
            return;

        $ids = $_POST['selection'];
        $criteria = new CDbCriteria;
        $criteria->addInCondition('id', $ids);
        if (AdForm::model()->deleteAll($criteria))
            Yii::app()->user->setFlash('success', Yii::t('app', 'Delete Success'));
        echo CJSON::encode(['result' => true]);
    }

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer $id the ID of the model to be loaded
	 * @return AdForm the loaded model
	 * @throws CHttpException
	 */
	public function loadModel($id)
	{
		$model=AdForm::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param AdForm $model the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='banner-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
}
